package com.lrkj.workorder.service.impl;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import com.lrkj.common.annotation.Log;
import com.lrkj.common.constant.WorkorderConstants;
import com.lrkj.common.core.domain.entity.SysUser;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.LrkjDateUtil;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.utils.SerialNumUtil;
import com.lrkj.property.domain.Room;
import com.lrkj.property.service.IRoomService;
import com.lrkj.workorder.domain.WorkOrder;
import com.lrkj.workorder.domain.WorkOrderLog;
import com.lrkj.workorder.domain.WorkOrderType;
import com.lrkj.workorder.domain.vo.WorkOrderVo;
import com.lrkj.workorder.mapper.WorkOrderMapper;
import com.lrkj.workorder.service.IWorkOrderLogService;
import com.lrkj.workorder.service.IWorkOrderService;
import com.lrkj.workorder.service.IWorkOrderTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 工单管理Service业务层处理
 *
 * @author yajun_ren
 * @date 2022-04-21
 */
@Service
public class WorkOrderServiceImpl implements IWorkOrderService {
    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private IWorkOrderLogService workOrderLogService;

    @Autowired
    private IWorkOrderTypeService workOrderTypeService;

    @Autowired
    private IRoomService roomService;


    //一天的毫秒数
   private final long d = 1000 * 24 * 60 * 60;
    //一小时的毫秒数
    private final long h = 1000 * 60 * 60;
    //一分钟的毫秒数
    private final long m = 1000 * 60;


    /**
     * 查询工单管理
     *
     * @param id 工单管理ID
     * @return 工单管理
     */
    @Override
    public WorkOrder selectWorkOrderById(String id) {
        return workOrderMapper.selectWorkOrderById(id);
    }

    /**
     * 查询工单管理列表
     *
     * @param workOrder 工单管理
     * @return 工单管理
     */
    @Override
    public List<WorkOrder> selectWorkOrderList(WorkOrder workOrder) {
        return workOrderMapper.selectWorkOrderList(workOrder);
    }

    /**
     * 新增工单管理
     *
     * @param workOrder 工单管理
     * @return 结果
     */
    @Override
    public int insertWorkOrder(WorkOrder workOrder) {
        WorkOrderType workOrderType = new WorkOrderType();
        if (StringUtils.isNotEmpty(workOrder.getOrderType())) {
            workOrderType = workOrderTypeService.selectWorkOrderTypeById(workOrder.getOrderType());
        }
        Room room = roomService.selectRoomById(workOrder.getRoomId());
        workOrder.setId(IdUtils.simpleUUID());
        workOrder.setCustomId(room.getOwnerId());
        workOrder.setStatus(WorkorderConstants.work_order_status_10);
        WorkOrderLog workOrderLog =new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_FQGD, "发起工单");
        workOrderLog.setOperationPersonId(workOrder.getCharterMemberId());
        workOrderLog.setOperationPersonName(workOrder.getCharterMemberName());
        workOrderLogService.insertWorkOrderLog(workOrderLog);
        workOrder.setNo(SerialNumUtil.getNo(workOrderType.getTypeCode() + LrkjDateUtil.getFormatTimeString(new Date(), "yyyyMM"), 5));
        workOrder.setCreateTime(DateUtils.getNowDate());
        return workOrderMapper.insertWorkOrder(workOrder);
    }

    /**
     * 修改工单管理
     *
     * @param workOrder 工单管理
     * @return 结果
     */
    @Override
    public int updateWorkOrder(WorkOrder workOrder) {
        workOrder.setUpdateTime(DateUtils.getNowDate());
        return workOrderMapper.updateWorkOrder(workOrder);
    }

    /**
     * 批量删除工单管理
     *
     * @param ids 需要删除的工单管理ID
     * @return 结果
     */
    @Override
    public int deleteWorkOrderByIds(String[] ids) {
        return workOrderMapper.deleteWorkOrderByIds(ids);
    }

    /**
     * 删除工单管理信息
     *
     * @param id 工单管理ID
     * @return 结果
     */
    @Override
    public int deleteWorkOrderById(String id) {
        return workOrderMapper.deleteWorkOrderById(id);
    }

    @Override
    @Transactional
    public int sendOrders(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        if(!oldWorkOrder.getStatus().equals(WorkorderConstants.work_order_status_10)){
            throw new BaseException("工单已分配,请刷新页面。");
        }
        oldWorkOrder.setReceivingPersonId(workOrder.getReceivingPersonId());
        oldWorkOrder.setReceivingPersonName(workOrder.getReceivingPersonName());
        oldWorkOrder.setStatus(WorkorderConstants.work_order_status_20);
        oldWorkOrder.setUpdateBy(user.getNickName());
        oldWorkOrder.setUpdateTime(DateUtils.getNowDate());
        workOrderMapper.updateWorkOrder(oldWorkOrder);
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_PD, String.format("由%s进行派单", user.getNickName())));
        //TODO 这里应该是是否开启 自动接单
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_JD, String.format("由%s进行接单", oldWorkOrder.getReceivingPersonName())));
        return 1;
    }

    @Override
    public int urgeOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_CD, String.format("由%s进行催单", user.getNickName())));
        //TODO 这里需要把催单信息 添加到我的消息中  发起人是当前登录人, 接收人是 接单人,和协办人
        return 1;
    }

    @Override
    public int jointlyOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setJointlyPersonId(workOrder.getJointlyPersonId());
        oldWorkOrder.setJointlyPersonName(workOrder.getJointlyPersonName());
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_XB, String.format("由%s发起让%s进行协办", user.getNickName(),workOrder.getJointlyPersonName())));
        //TODO 这里需要把催单信息 添加到我的消息中  发起人是当前登录人, 接收人是 接单人,和协办人
        return 1;
    }

    /**
     * 办结
     * @param workOrder
     * @return
     */
    @Override
    public int conCludeOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setCharterMemberId(workOrder.getCharterMemberId());
        oldWorkOrder.setCharterMemberName(workOrder.getCharterMemberName());
        oldWorkOrder.setStatus(WorkorderConstants.work_order_status_40);
        oldWorkOrder.setUpdateBy(user.getNickName());
        oldWorkOrder.setUpdateTime(DateUtils.getNowDate());

            //挂单过
            if (oldWorkOrder.getSuspendPersonTime()!=null){
                //(挂单时间-发起时间)
                long timeDiff = oldWorkOrder.getSuspendPersonTime().getTime() - oldWorkOrder.getCharterTime().getTime();

                // 计算差多少天
                long day = timeDiff / d;

                // 计算差多少小时
                long hour = timeDiff % d / h;

                // 计算差多少分钟
                long min = timeDiff % d % h / m;

               // (结束时间-挂单结束时间)
                long endtimeDiff =workOrder.getConcludePersonTime().getTime() - oldWorkOrder.getEndSuspendTime().getTime();

                // 计算差多少天
                long Endday = endtimeDiff / d;

                // 计算差多少小时
                long Endhour = endtimeDiff % d / h;

                // 计算差多少分钟
                long Endmin = endtimeDiff % d % h / m;

                String time  = (day+Endday)+"天"+(hour+Endhour)+"小时"+(min+Endmin)+"分钟";

                oldWorkOrder.setFormatBetween(time);
            }else{
                String formatBetween = DateUtil.formatBetween(workOrder.getConcludePersonTime(), oldWorkOrder.getCharterTime(), BetweenFormater.Level.MINUTE);
                oldWorkOrder.setFormatBetween(formatBetween);
            }

            oldWorkOrder.setStatus(WorkorderConstants.work_order_status_40);
            workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_BJ, String.format("由%s进行办结", workOrder.getCharterMemberName())));

             workOrderMapper.updateWorkOrder(oldWorkOrder);

             return 1;
    }


    /**
     * 回访
     * @param workOrder
     * @return
     */
    @Override
    public int returnOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        //oldWorkOrder.setReturnPersonId(workOrder.getReturnPersonId());
       // oldWorkOrder.setReturnPersonName(workOrder.getReturnPersonName());
        oldWorkOrder.setUpdateBy(user.getNickName());
        oldWorkOrder.setUpdateTime(DateUtils.getNowDate());
        if (workOrder.getReturnSatisfaction().equals("10")) {
            oldWorkOrder.setStatus(WorkorderConstants.work_order_status_50);
            workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_HF, String.format("由%s进行回访", user.getNickName())));

            workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_WJ, String.format("客户满意，由%s进行工单完结", user.getNickName())));
        } else {
        //客户不满意
        oldWorkOrder.setStatus(WorkorderConstants.work_order_status_70);
        oldWorkOrder.setReturnSatisfaction(workOrder.getReturnSatisfaction());
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_FX, String.format("由%s发起让%s进行返修", user.getNickName(),workOrder.getReceivingPersonName())));
        }

        workOrderMapper.updateWorkOrder(oldWorkOrder);

        return 1;
    }

    @Override
    public int careOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        //转交人
        oldWorkOrder.setCarePersonId(workOrder.getCarePersonId());
        oldWorkOrder.setCarePersonName(workOrder.getCarePersonName());
        oldWorkOrder.setCareReason(workOrder.getCareReason());
        oldWorkOrder.setCarePersonTime(workOrder.getCarePersonTime());
        //原接单人
        oldWorkOrder.setCareRawPersonId(oldWorkOrder.getReceivingPersonId());
        oldWorkOrder.setCareRawPersonName(oldWorkOrder.getReceivingPersonName());

        oldWorkOrder.setReceivingPersonId(workOrder.getCarePersonId());
        oldWorkOrder.setReceivingPersonName(workOrder.getCarePersonName());

        oldWorkOrder.setUpdateBy(user.getNickName());
        oldWorkOrder.setUpdateTime(DateUtils.getNowDate());

        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_ZJ, String.format("由%s发起由原接单人%s转交至%s", user.getNickName(),workOrder.getReceivingPersonName(),workOrder.getCarePersonName())));

        workOrderMapper.updateWorkOrder(oldWorkOrder);
        return 1;
    }

    /**
     * 取消
     * @param workOrder
     * @return
     */
    @Override
    public int chargebackOrder(WorkOrder workOrder) {

        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setChargebackPersonId(workOrder.getChargebackPersonId());
        oldWorkOrder.setChargebackPersonName(workOrder.getChargebackPersonName());
        oldWorkOrder.setChargebackTime(workOrder.getChargebackTime());
        oldWorkOrder.setChargebackContent(workOrder.getChargebackContent());
        oldWorkOrder.setStatus("60");
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_QX, String.format("由%s进行取消", workOrder.getChargebackPersonName())));
        workOrderMapper.updateWorkOrder(oldWorkOrder);
        return 1;
    }

    /**
     * 挂单
     * @param workOrder
     * @return
     */
    @Override
    public int suspendOrder(WorkOrder workOrder) {
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setSuspendPersonId(workOrder.getSuspendPersonId());
        oldWorkOrder.setSuspendPersonName(workOrder.getSuspendPersonName());
        oldWorkOrder.setSuspendPersonReason(workOrder.getSuspendPersonReason());
        oldWorkOrder.setSuspendPersonTime(workOrder.getSuspendPersonTime());
        oldWorkOrder.setStatus("30");
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_GD, String.format("由%s进行挂单",workOrder.getSuspendPersonName())));
        workOrderMapper.updateWorkOrder(oldWorkOrder);

        return 1;
    }

    /**
     * 取消挂单
     * @param workOrder
     * @return
     */
    @Override
    public int endSuspendOrder(WorkOrder workOrder) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());

        oldWorkOrder.setStatus("20");
        oldWorkOrder.setEndSuspendTime(LrkjDateUtil.getCurrentDate());
        oldWorkOrder.setUpdateBy(user.getNickName());
        oldWorkOrder.setUpdateTime(DateUtils.getNowDate());
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_GD, String.format("由%s进行取消挂单",user.getNickName())));
        workOrderMapper.updateWorkOrder(oldWorkOrder);
        return 1;
    }

    /**
     * 返修
     * @param workOrder
     * @return
     */
    @Override
    public int repairOrder(WorkOrder workOrder) {
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setStatus("20");
        oldWorkOrder.setRepairPersonId(workOrder.getRepairPersonId());
        oldWorkOrder.setRepairPersonName(workOrder.getRepairPersonName());
        oldWorkOrder.setRepairPersonTime(workOrder.getRepairPersonTime());
        oldWorkOrder.setRepairContent(workOrder.getRepairContent());
        oldWorkOrder.setFormatBetween(null);
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_GD, String.format("由%s进行返修",workOrder.getRepairPersonName())));
        workOrderMapper.updateWorkOrder(oldWorkOrder);
        return 1;
    }

    @Override
    public List<WorkOrder> selWorkOrderAll(WorkOrder workOrder) {

        List<WorkOrder> workOrderList = workOrderMapper.selectWorkOrderList(workOrder);
        workOrderList.stream().forEach(x->{
            WorkOrderLog workOrderLog=new WorkOrderLog();
            workOrderLog.setWorkOrderId(x.getId());
            List<WorkOrderLog> logList = workOrderLogService.selectWorkOrderLogList(workOrderLog);
            x.setLogList(logList);
        });
        return workOrderList;
    }

    @Override
    public int retreatOrder(WorkOrder workOrder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrder oldWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        oldWorkOrder.setReceivingPersonId("");
        oldWorkOrder.setReceivingPersonName("");
        oldWorkOrder.setStatus("10");
        oldWorkOrder.setRetreatContent(workOrder.getRetreatContent());
        workOrderLogService.insertWorkOrderLog(new WorkOrderLog(workOrder.getId(), WorkorderConstants.order_operation_type_TD, String.format("由%s进行退单",user.getNickName())));
        workOrderMapper.updateWorkOrder(oldWorkOrder);
        //TODO 退单后工单状态改为待分配
        return 1;
    }

    @Override
    public List<WorkOrder> indexShow(String time) {
        return workOrderMapper.indexShowCountWorkOrder(time);
    }

    @Override
    public List<WorkOrderVo> selCountByStatus() {
        return workOrderMapper.selCountByStatus();
    }

    /**
     * 批量新增工单管理信息
     *
     * @param workOrders 工单管理对象
     */
    public int batchAddData(List<WorkOrder> workOrders) {
        return workOrderMapper.batchAddData(workOrders);
    }
}
